﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Ttifa.Infrastructure;

namespace Ttifa.WebApiBase
{
    /// <summary>
    /// String 处理结果
    /// </summary>
    public class StringMediaTypeFormatter : MediaTypeFormatter
    {
        /// <summary>
        /// 
        /// </summary>
        public StringMediaTypeFormatter()
        {
            //设置支持的编码格式
            base.SupportedEncodings.Clear();

            base.SupportedEncodings.Add(Encoding.UTF8);
            base.SupportedEncodings.Add(Encoding.Unicode);
            base.SupportedEncodings.Add(Encoding.Default);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override bool CanReadType(Type type) => false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override bool CanWriteType(Type type) => true;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <param name="writeStream"></param>
        /// <param name="content"></param>
        /// <param name="transportContext"></param>
        /// <returns></returns>
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(writeStream, Encoding.UTF8)) sw.Write(value.ToString());

                return Task.FromResult<AsyncVoid>(new AsyncVoid());
            }
            catch (Exception exception)
            {
                TaskCompletionSource<AsyncVoid> source = new TaskCompletionSource<AsyncVoid>();
                source.SetException(exception);

                return source.Task;
            }
        }
    }
}